<template>
    <div class="bi-date">
        <template v-if="popup" >
            <bi-input-handle  v-dropdown dropdown-body="body" dropdown-width="auto" 
                :status = "checkStatus"
                icon = "fa-calendar"
                :placeholder = "placeholder"
                :label = "valueLabel"
                :clear = "value != undefined"
                @clear="clearValue"
            >
            </bi-input-handle>
        </template>

        <div ref="body">
            <div class="bi-date-body" :class="{range:range}" @click.stop="()=>{}">
                <bi-calendar  
                :range = "range"
                v-model= "value"
                :year = "year_1"
                :month = "month_1"
                 
                select
                @change = "calendar_1_change"
                ref="calendar_1"
                ></bi-calendar>
                <bi-calendar v-if="range"
                :range = "range"
                v-model= "value"
                :year = "year_2"
                :month = "month_2"
                
                select
                ref="calendar_2"
                @change = "calendar_2_change"
                ></bi-calendar>
            </div>
        </div>
    </div>
</template>

<script>
import FieldMixin from '../fieldMixin.js';
import BiCalendar from '../control/calendar.vue';
export default{
    mixins:[FieldMixin],
    components:{
        BiCalendar
    },
    data(){

         
        let year_1 = new Date().getFullYear();
        let month_1 = new Date().getMonth() +1;

        let year_2 = year_1;
        let month_2 = month_1+1;



        return {
            valueLabel:'',
            max:undefined,
            min:undefined,
            year_1,
            month_1,
            year_2,
            month_2,
        }
    },
    props:{
        range:{
            type:Boolean,
            default:false
        },
        popup:{
            type:Boolean,
            default:true
        },
        rangeText:{
            type:String,
            default:'到'
        }
    },
    watch:{
    
    },
    computed:{
        value:{
            get(){

               let  clearTime = (date)=>{
                    return new Date(
                        date.getFullYear(),
                        date.getMonth(),
                        date.getDate()
                    )
                }

                let val  = this.modelValue;

                if (val == undefined) return undefined;

                if (this.range) {

                    if (!(val instanceof Array)){
                        console.error('range模式下modelValue必须为数组');
                        return undefined;
                    }
                
                    if  (val.length == 0) return undefined;

                    let value = [];

                    if (val.length >= 1){
                        let date_1 = clearTime(new Date(val[0]));
                        console.log(val[0],date_1);
                        if (isNaN(date_1.getTime())){
                            console.error('range模式下modelValue数组第一项格式错误');
                            return undefined;
                        }
                        value.push(date_1);
                    }
                   
                    if (val.length == 2){
                        let date_2 = clearTime(new Date(val[1]));
                        if (isNaN(date_2.getTime())){
                            console.error('range模式下modelValue数组第二项格式错误');
                            return undefined;
                        }else{
                            value.push(date_2);
                        }

                        if (value[0].getTime() > value[1].getTime()){
                            console.error('range模式下modelValue数组第一项不能大于第二项');
                            return undefined;
                        }
                    }
                    
                    return value;
                }else{
                    if (typeof val != 'string'){
                        console.error('modelValue格式错误');
                        return undefined;
                    }

                    let date = new Date(val);
                    if (isNaN(date.getTime())){
                        console.error('modelValue格式错误');
                        return undefined;   
                    }else{



                        return date;
                    }
                }

            },
            set(val){

                let format = 'YYYY-MM-DD';
                let value = '';
                this.valueLabel = '';
                if (this.range){

                    if (val == undefined){
                        value = [];
                       
                    }
                    else{
                        value = [];
                        if (val[0]){
                            this.valueLabel = this.formatDate(val[0],format) + ' ' +  this.rangeText + ' '; 
                            value.push(this.formatDate(val[0],format));
                        } 
                        if (val[1]){
                            this.valueLabel += this.formatDate(val[1],format);
                            value.push(this.formatDate(val[1],format));
                           if (typeof(this.$refs['body'].hide) ==  'function') this.$refs['body'].hide();
                        }
                    }
                     
                    this.$refs['calendar_1'].updateDayClass(val);
                    this.$refs['calendar_2'].updateDayClass(val);

                    

                }else{
                    
                    if (val!=undefined){
                        value = this.formatDate(val,format);
                        if (typeof(this.$refs['body'].hide) ==  'function') this.$refs['body'].hide();
                    }

                    this.valueLabel = value;
                }

                
                this.$emit('update:modelValue',value);
                this.$emit('change',value);
                this.valueChange(value);
            }
        },
    },
    methods:{
        formatDate(date,format){
            const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
            const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

            function padZero(value) {
                return value < 10 ? `0${value}` : value;
            }

            return format
                .replace('YYYY', date.getFullYear())
                .replace('MM', padZero(date.getMonth() + 1))
                .replace('DD', padZero(date.getDate()))
                .replace('HH', padZero(date.getHours()))
                .replace('mm', padZero(date.getMinutes()))
                .replace('ss', padZero(date.getSeconds()))
                .replace('ddd', dayNames[date.getDay()])
                .replace('MMMM', monthNames[date.getMonth()]);
            
        },
        updateCalendar(value){
            
            if (value == undefined) return;
             
            if (this.range){

                //判断值是否在同一个年月
                if (value[0].getFullYear() == value[1].getFullYear() && value[0].getMonth() == value[1].getMonth()){
                    this.year_1 =  value[0].getFullYear();
                    this.month_1 = value[0].getMonth() +1;
                    this.year_2 = value[1].getFullYear();
                    this.month_2 = value[1].getMonth() + 2;
                    this.cross = false;
                    this.value_1 = value;

                }else{
                    this.year_1 =  value[0].getFullYear();
                    this.month_1 = value[0].getMonth() + 1;
                    this.year_2 =  value[1].getFullYear();
                    this.month_2 = value[1].getMonth() + 1;
                    this.cross = true;

                    this.value_1 = [value[0],true];
                    this.value_2 = [true,value[1]];
                }

            }else{
                this.year_1 = value.getFullYear();
                this.month_1 = value.getMonth()+1;
            }
        },
        calendar_1_change(res){

            this.year_1 = res.year;
            this.month_1 = res.month;

            if (res.year > this.year_2 || (res.year == this.year_2 && res.month >= this.month_2)){
                if (res.month == 12 ){
                    this.month_2 = 1;
                    this.year_2 = res.year+1;
                }else{
                    this.year_2 =  res.year;
                    this.month_2 = res.month + 1;
                }
            }


        },
        calendar_2_change(res){
            this.year_2 = res.year;
            this.month_2 = res.month;

            if (res.year_2 < this.year_1 || (res.year == this.year_1 && res.month <= this.month_1)){
                if (res.month == 1){
                    this.month_1 = 12;
                    this.year_1 = res.year-1;
                }else{
                    this.year_1 =  res.year;
                    this.month_1 = res.month - 1;
                }
            }
        },
        clearValue(){
            this.value = undefined;
        }
    },
    mounted(){
        this.updateCalendar();
    }
}
</script>


<style>
.bi-date-body{
    padding: 10px;
}
.bi-date-body.range{
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.bi-date-body.range .bi-calendar-box{
    flex: 1;
}
</style>